package com.lanyam.travel.base.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lanyam.travel.base.dao.UserMapper;
import com.lanyam.travel.base.entity.DistrRecord;
import com.lanyam.travel.base.entity.DistrUser;
import com.lanyam.travel.base.entity.User;
import com.lanyam.travel.base.entity.vo.DistrSettingVo;
import com.lanyam.travel.base.entity.vo.DistrUserVo;
import com.lanyam.travel.base.dao.DistrUserMapper;
import com.lanyam.travel.base.entity.vo.UserVo;
import com.lanyam.travel.base.service.IDistrSettingService;
import com.lanyam.travel.base.service.IDistrUserService;
import com.lanyam.travel.base.service.UserService;
import com.lanyam.travel.base.utils.JSONResult;
import com.lanyam.travel.base.utils.MapUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;
import javax.annotation.Resource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.util.StringUtils;


@Service
@Transactional
@Slf4j
public class DistrUserServiceImpl implements IDistrUserService {

    @Resource
    private DistrUserMapper distrUserMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public IPage<DistrUserVo> getPageDistrUser (Map<String, Object> queryMap, Integer page, Integer rows) {
        Page<DistrUserVo> pageSize = new Page<DistrUserVo>(page, rows);
        Page<DistrUserVo> pageInfo = distrUserMapper.getPage(pageSize, queryMap);
        return pageInfo;
    }

    @Override
    public void addDistrUser(DistrUser distrUser) {
        Map<String, Object> queryMap =new HashMap<>();
        queryMap.put("user_id",distrUser.getUserId());
        List c = distrUserMapper.selectByMap(queryMap);
        if(CollectionUtils.isNotEmpty(c)){
            throw new RuntimeException("此用户已是分销商,不能重复添加");
        }
        if(StringUtils.isEmpty(distrUser.getFatherUserid()) || distrUser.getFatherUserid().equals("#")){
            distrUser.setFatherUserid(null);
            if(distrUser.getDislevel() == null){
                distrUser.setDislevel(1);
            }
        }else{
            if(distrUser.getDislevel() == null){
                List<DistrUser> selectFather = distrUserMapper.selectByMap(queryMap);
                if(CollectionUtils.isNotEmpty(selectFather)){
                    DistrUser father = selectFather.get(0);
                    distrUser.setDislevel(father.getDislevel()+1);
                }
            }
        }
        distrUserMapper.insert(distrUser);
    }

    @Override
    public void updateDistrUser(DistrUser distrUser) {
        Integer auditStatus = distrUser.getAuditStatus();
        if (auditStatus == 1)
            distrUser.setInviteCode(null);
        else if (auditStatus == 9)
            distrUser.setInviteCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0,8).toUpperCase());
        distrUserMapper.updateById(distrUser);
    }

    @Override
    public void delById(String id) {
        distrUserMapper.delById(id);
    }

    @Override
    public IPage<DistrUserVo> getPageGroupByTeam(Map<String, Object> queryMap, Integer page, Integer rows) {
        Page<DistrUserVo> pageSize = new Page<DistrUserVo>(page, rows);
        Page<DistrUserVo> pageInfo = distrUserMapper.getPageGroupByTeam(pageSize, queryMap);
        return pageInfo;
    }

	@Override
	public List<DistrUser> getAllDistrUser() {
		// TODO Auto-generated method stub
		List<DistrUser> selectList = distrUserMapper.selectList(null);
		return selectList;
	}

    @Override
    public DistrUserVo getDistrUserByUserId(String userId) {
        return distrUserMapper.getDistrUserByUserId(userId);
    }

    @Override
    public IPage<DistrUserVo> getListByFatherUserId(Map<String, Object> queryMap, Integer page, Integer rows) {
        /*// TODO 设置当前用户身份信息（如果仅管理员能使用该接口，则无需求改）到map
        User currentUser = userService.getCurrentUser();
        if (currentUser != null) {
            if (currentUser.getRoleId() != null && currentUser.getRoleId().equals("2")) {
                queryMap.put("roleType", "admin");
            } else {
                queryMap.put("roleType", "notAdmin");
                queryMap.put("loginUser", currentUser.getId());
            }
        }*/
        Page<DistrUserVo> pageSize = new Page<DistrUserVo>(page, rows);
        Page<DistrUserVo> pageInfo = distrUserMapper.getListByFatherUserId(pageSize, queryMap);
        return pageInfo;
    }

    @Override
    public void supplyDistr(DistrUserVo distrUser) {
        String userId = distrUser.getUserId();
        String inviteCode = distrUser.getInviteCode();
        User user = userMapper.getUserById(userId);
        if (userId==null || userId.trim().equals("")) {
            throw new RuntimeException("用户id不能未空！");
        }
        // 判断当前用户是否已经提交申请
        int countByUserId = distrUserMapper.getCountByUserId(userId);
        if (countByUserId > 0)
            throw new RuntimeException("当前用户已经申请，不能重复提交！");
        // 根据分销码添加分销商信息
        distrUser.setId(UUID.randomUUID().toString().replaceAll("-","").toUpperCase());
//        distrUser.setInviteCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0,8).toUpperCase());
        distrUser.setInviteCode(null);
        distrUser.setAuditStatus(0);
        distrUser.setUserName(user.getName());
        distrUser.setNickName(user.getNickName());
        if (inviteCode == null || inviteCode.trim().equals("")) {
            distrUser.setTeamId(UUID.randomUUID().toString().replaceAll("-",""));
            distrUser.setDislevel(0);
            distrUserMapper.insert(distrUser);
        } else {
            DistrUserVo byInviteCode = distrUserMapper.getByInviteCode(inviteCode);
            if (byInviteCode == null)
                throw new RuntimeException("邀请码填写错误，请重新检查！");
            Integer dislevel = byInviteCode.getDislevel();
            if (dislevel == null) {
                System.out.println(">>>>>>>>>>>>>>>>>>> 异常分销用户id："+byInviteCode.getId());
                throw new RuntimeException("该分销商层级异常，请联系管理员！");
            }
            if (dislevel > 3)
                throw new RuntimeException("该分销商无法邀请新用户！");
            // 分销散户直接通过，无需审核
            if (dislevel == 3)
                distrUser.setAuditStatus(9);
            distrUser.setFatherUserid(byInviteCode.getId());
            distrUser.setDislevel(dislevel+1);
            distrUser.setTeamId(byInviteCode.getTeamId());
            distrUserMapper.insert(distrUser);
        }
    }

    @Override
    public void addDistrUserByAdmin(DistrUser du) {
        String userId = du.getUserId();
        int countByUserId = distrUserMapper.getCountByUserId(userId);
        if (countByUserId > 0)
            throw new RuntimeException("当前用户已经是分销商用户，不能重复添加！");
        User user = userMapper.getUserById(userId);
        if (user == null)
            throw new RuntimeException("当前用户信息异常，请联系管理员！");
        DistrUser distrUser = new DistrUser();
        distrUser.setId(UUID.randomUUID().toString().replaceAll("-",""));
        distrUser.setInviteCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0,8).toUpperCase());
        distrUser.setAuditStatus(9);
        distrUser.setUserName(user.getName());
        distrUser.setNickName(user.getNickName());
        distrUser.setDislevel(du.getDislevel());
        distrUser.setUserId(userId);
        distrUser.setAmount(BigDecimal.ZERO);
        distrUserMapper.insert(distrUser);
    }

    @Override
    public IPage<UserVo> getUserListAddDistrUser(Map<String, Object> queryMap, Integer page, Integer rows) {
        Page<UserVo> pageSize = new Page<>(page, rows);
        Page<UserVo> pageInfo = distrUserMapper.getUserListAddDistr(pageSize, queryMap);
        return pageInfo;
    }


    @Override
    public List<DistrUserVo> getDistrMembers(String userId){
        DistrUserVo userVo = distrUserMapper.getDistrUserByUserId(userId);
        List<DistrUserVo> members =distrUserMapper.getDistrUsersByTeamId(userVo.getTeamId());
        return members;
    }
}